package com.waming.ards.uninstall;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.stereotype.Component;
import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration;

@Component
public class ApplicationClosedEventListener implements ApplicationListener<ContextClosedEvent> {
	private static Logger logger = LoggerFactory.getLogger(ApplicationClosedEventListener.class);
	@Autowired
	private NacosDiscoveryProperties nacosDiscoveryProperties;
	@Autowired
	private NacosAutoServiceRegistration nacosAutoServiceRegistration;
	@Override
	public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
        String service = nacosDiscoveryProperties.getService();
        String groupName = nacosDiscoveryProperties.getGroup();
        String clusterName = nacosDiscoveryProperties.getClusterName();
        String ip = nacosDiscoveryProperties.getIp();
        int port = nacosDiscoveryProperties.getPort();
        logger.info("application accepts the shutdown request, serviceName:{}, groupName:{}, clusterName:{}, ip:{}, port:{}", service, groupName, clusterName, ip, port);
		try {
			//deregister service and nacos service shutDown
			nacosAutoServiceRegistration.destroy();
		} catch (Exception e) {
			e.printStackTrace();
		}
	    logger.info("nacos service registry close serviceName:{}, groupName:{}, clusterName:{}, ip:{}, port:{} finish",service, groupName, clusterName, ip, port);
	}
}
